import axios from 'axios'

import router from '@/router'
import store from '@/store'
import { Toast } from '@/utils'

// 错误处理
const errorHandler = (error) => {
  const code = error.statusCode || error.code
  switch (code) {
    case 400:
      Toast.fail(error.data || '请求错误')
      break
    case 401:
      Toast.fail('未授权')
      router.replace('/login')
      break
    case 403:
      Toast.fail('未授权')
      router.replace('/login')
      break
    case 404:
      Toast.fail('请求路径有误')
      break
    case 500:
      Toast.fail(error.data || '服务器发生错误')
      break
  }
}

/**
 * 封装axios
 * @param {*} config
 * @returns
 */
const request = (config) => {
  return new Promise((resolve) => {
    // 创建axios的实例
    const instance = axios.create({
      baseURL: 'http://localhost:3000',
      timeout: 5000
    })

    // 请求拦截
    instance.interceptors.request.use((config) => {
      // 添加loading图标
      Toast.loading()
      // 设置token
      config.headers.Authorization = 'Bearer ' + store.state.token
      return config
    })

    // 响应拦截
    instance.interceptors.response.use(
      (response) => {
        Toast.clear()
        if (response.data.code == 200 || response.data.code == 201) {
          resolve(response.data.data)
          return
        }
        errorHandler(response.data)
      },
      (err) => {
        Toast.clear()
        errorHandler(err.response.data)
      }
    )

    return instance(config)
  })
}

export default request
